package com.manor.paradise.activity


import android.annotation.TargetApi
import android.content.Context
import android.graphics.Color
import android.hardware.Sensor
import android.hardware.SensorManager
import android.os.Build
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.util.DisplayMetrics
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.bumptech.glide.Glide
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.opensource.svgaplayer.SVGAImageView
import com.manor.common.activity.AbsActivity
import com.manor.common.http.JHttpCallback
import com.manor.common.ktx.toBean
import com.manor.common.utils.SpUtil
import com.manor.common.utils.SvgaUtils
import com.manor.common.utils.ToastUtil
import com.manor.common.utils.*
import com.manor.paradise.R
import com.manor.paradise.bean.*
import com.manor.paradise.dialog.HireElvesPopup
import com.manor.paradise.dialog.MineInfoPopup
import com.manor.paradise.dialog.WizardDetailsPopup
import com.manor.paradise.http.ElvesHttpConst
import com.manor.paradise.http.ElvesHttpUtil
import com.manor.paradise.util.ReboundUtil
import com.manor.paradise.view.MineInfoListener
import kotlinx.android.synthetic.main.activity_mine.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigDecimal
import java.util.*

/**
 * 能量矿山 / 淘米矿山
 */
class MineActivity : AbsActivity(), View.OnClickListener {

    internal var im_list: MutableList<ImageView> = ArrayList()
    internal var svga_list: MutableList<SVGAImageView> = ArrayList()
    lateinit var reboundUtil: ReboundUtil



    override fun getLayoutId(): Int {
        return R.layout.activity_mine
    }


    override fun main() {
        super.main()
        ImmersionBar.with(this)
                .autoStatusBarDarkModeEnable(true)
//                .hideBar(BarHide.FLAG_HIDE_STATUS_BAR)
                .init()
        reboundUtil = ReboundUtil()
        initView()

    }


    private fun initView() {
        val dm = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(dm)
        EventBus.getDefault().register(this)

        im_back.setOnClickListener { finish() }

        im_hysm.setOnClickListener(this)
        im_xcpy.setOnClickListener(this)
        im_ayxd.setOnClickListener(this)
        im_gmyd.setOnClickListener(this)
        im_gzcz.setOnClickListener(this)
        im_hasl.setOnClickListener(this)
        im_mftf.setOnClickListener(this)
        im_smzs.setOnClickListener(this)
        im_cyhd.setOnClickListener(this)

        im_list.add(im_cyhd)
        im_list.add(im_smzs)
        im_list.add(im_mftf)
        im_list.add(im_hasl)
        im_list.add(im_gzcz)
        im_list.add(im_gmyd)
        im_list.add(im_ayxd)
        im_list.add(im_xcpy)
        im_list.add(im_hysm)
        im_list.add(im_mf_tag)
        for (im_lq in im_list) {
            if (im_lq != im_mf_tag) {
                im_lq.setOnTouchListener(View.OnTouchListener { v, event ->
                    // 触摸时取消动画，并缩小，有按下的感觉
                    if (event.action == MotionEvent.ACTION_DOWN || event.action == MotionEvent.ACTION_MOVE) {
                        im_lq.setScaleX(0.9f)
                        im_lq.setScaleY(0.9f)
                        if (im_lq.getAnimation() != null) {
                            im_lq.getAnimation().cancel()
                        }
                    } else { // 松手后，恢复大小，并继续呼吸效果
                        im_lq.setScaleX(1.0f)
                        im_lq.setScaleY(1.0f)
                        if (im_lq.getAnimation() != null) {
                            im_lq.getAnimation().start()
                        }
                    }

                    false
                })
            }
        }


        svga_list.add(svag1)
        svga_list.add(svag2)
        svga_list.add(svag3)
        svga_list.add(svag4)
        svga_list.add(svag5)
        svga_list.add(svag6)
        svga_list.add(svag7)
        svga_list.add(svag8)
        svga_list.add(svag9)



        if (!SpUtil.getInstance().getBooleanValue(SpUtil.FRIRYLAND_BGETSPIRIT)) {
            reboundUtil.setReboundView(im_cyhd)
        } else {
            im_mf_tag.visibility = View.GONE
            im_list.remove(im_mf_tag)
        }

        initData()

    }

    private fun initData() {
        ElvesHttpUtil.getSpiritCount(object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code != 200) {
                    ToastUtil.show(msg)
                    return
                }
                if (StringUtil.isEmpty(info))
                    return
                var bean = info.toBean<SpiritBean>()
                ll_ks?.setVisible(true)
                tv_ks?.text = "我有米粒：${bean.crystalOre}"
                tv_sj?.text = "我有能量：${bean.crystal}"

                val list: List<SpiritCount> = bean.spiritCounts
                setSCount(list, listOf(tv_cyhd, tv_smzs, tv_mftf, tv_gmyd, tv_gzcz, tv_hasl, tv_ayxd, tv_xcpy, tv_hysm))

            }

            override fun onError() {
                super.onError()

            }
        })
    }

    private fun setSCount(list: List<SpiritCount>, tvArr: List<TextView?>) {
        for (i in list.indices) {
            list.findLast { it.spiritId == (i + 1).toString() }?.apply {
                val p = if (i == 0) "免费" else price
                tvArr[i]?.text = "${spiritCount}/${sameNum}  $p"
                tvArr[i]?.visibility = View.VISIBLE
            }
        }
    }

    /**
     * 我雇佣的精灵（精灵矿山）
     */
    private fun setJlIndex() {
        for (svgaImageView in svga_list) {
            svgaImageView.stopAnimation()
        }
        ElvesHttpUtil.getSpiritHave(object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code != 200) {
                    ToastUtil.show(msg)
                    return
                }
                //val l = info.toBeanList<MineIndexBean>()
                var list = JSON.parseArray(info, MineIndexBean::class.java)
                for (index in list.indices) {
                    if (list[index].isBhave) {
                        if (index < svga_list.size) {
                            KLog.e("getSpiritHave-svgaUtils1", index)
                            val svgaUtils1 = SvgaUtils(this@MineActivity, svga_list[index])
                            svgaUtils1.initAnimator();
                            svgaUtils1.startAnimator("pic_gzdx");
                        }
                    }

                }
            }

            override fun onError() {
                super.onError()

            }
        })
    }

    override fun onResume() {
        super.onResume()
        setJlIndex()
    }

    override fun onPause() {
        super.onPause()
        for (svgaImageView in svga_list) {
            svgaImageView.stopAnimation()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPublishCommentEvent(msg: MsgBean) {
        if (msg.type == 0) {//免费雇佣
            im_mf_tag.visibility = View.GONE
            im_list.remove(im_mf_tag)
            getmf()
        }
        setJlIndex()
    }

    fun getmf() {
        val ss = SpannableString("您已拥有乌骨鸡，赶快到养殖场让它工作起来吧！")
        val foregroundColorSpan = ForegroundColorSpan(Color.parseColor("#CE2F69"))
        ss.setSpan(foregroundColorSpan, 11, 20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        XPopup.Builder(this)
                .asConfirm(null, ss) {
                    MyEmploymentActivity.forward(this, 0)
                }
                .show()
    }

    override fun onDestroy() {
        Glide.get(this).clearMemory()
        EventBus.getDefault().unregister(this);
        ElvesHttpUtil.cancel(ElvesHttpConst.POST_OPEN_SPIRIT_INFO)
        super.onDestroy()
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        val id = v?.id
        if (id == R.id.im_hysm) {
            setPopDialog(im_hysm)
        } else if (id == R.id.im_xcpy) {
            setPopDialog(im_xcpy)
        } else if (id == R.id.im_ayxd) {
            setPopDialog(im_ayxd)
        } else if (id == R.id.im_gmyd) {
            setPopDialog(im_gmyd)
        } else if (id == R.id.im_gzcz) {
            setPopDialog(im_gzcz)
        } else if (id == R.id.im_hasl) {
            setPopDialog(im_hasl)
        } else if (id == R.id.im_mftf) {
            setPopDialog(im_mftf)
        } else if (id == R.id.im_smzs) {
            setPopDialog(im_smzs)
        } else if (id == R.id.im_cyhd) {
            setPopDialog(im_cyhd)
        }
    }

    var type = true

    private fun setPopDialog(view: ImageView) {

        if (type) {
            type = false
            showWaitingDialog(false)
            ElvesHttpUtil.getMineralInfo(BigDecimal(view.tag.toString()), object : JHttpCallback() {
                override fun onSuccess(code: Int, msg: String, info: String) {
                    dismissWaitingDialog()
                    if (code != 200) {
                        ToastUtil.show(msg)
                        return
                    }

                    type = true
                    var mineInfoBean: MineInfoBean = GsonUtil.gsonToBean<MineInfoBean>(info, MineInfoBean::class.java)


                    XPopup.Builder(mContext)
                            .hasShadowBg(true)
                            .dismissOnTouchOutside(true)
                            .hasStatusBarShadow(false) //启用状态栏阴影
                            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                            .asCustom(HireElvesPopup(mineInfoBean, mContext))
                            .show()
                }

                override fun onError() {
                    super.onError()
                    dismissWaitingDialog()
                    type = true
                }
            })
        }
    }


    companion object {
        @TargetApi(Build.VERSION_CODES.KITKAT)
        fun isSupportStepCountSensor(context: Context): Boolean {
            // 获取传感器管理器的实例
            val sensorManager = context
                    .getSystemService(Context.SENSOR_SERVICE) as SensorManager
            val countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)
            return countSensor != null
        }
    }

}
